package com.idanchuang.component.core.config;

import com.idanchuang.component.core.enums.AesEnum;

import java.util.Objects;

public abstract class AbstractCryptConfigBean {

    /**
     * 加密类型
     */
    protected AesEnum aes;
    /**
     * 秘钥, 长度必须与 AesEnum 中的 secretKeyLength 一致
     */
    protected String secretKey;
    /**
     * 密文前缀
     */
    protected String prefix;

    public AbstractCryptConfigBean(AesEnum aes, String secretKey, String prefix) {
        this.aes = aes;
        this.secretKey = secretKey;
        this.prefix = prefix;
        checkAesEnum();
        checkSecretKeyLength();
        checkPrefix();
    }

    private void checkSecretKeyLength() {
        if (secretKey == null || secretKey.length() != aes.getSecretKeyLength()) {
            throw new RuntimeException("secretKey length not support, allow length: " + aes.getSecretKeyLength());
        }
    }

    private void checkAesEnum() {
        if (Objects.isNull(aes)) {
            throw new RuntimeException("crypt initialized failed");
        }
    }

    private void checkPrefix() {
        if (prefix == null) {
            throw new RuntimeException("prefix must be assigned");
        }
    }

    public AesEnum getAes() {
        return aes;
    }

    public void setAes(AesEnum aes) {
        this.aes = aes;
        checkAesEnum();
    }

    public String getSecretKey() {
        return secretKey;
    }

    public void setSecretKey(String secretKey) {
        this.secretKey = secretKey;
        checkSecretKeyLength();
    }

    public String getPrefix() {
        return prefix;
    }

    public void setPrefix(String prefix) {
        this.prefix = prefix;
        checkPrefix();
    }
}
